package v1

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model/mysql"
	"jwgin/service"
	ding "jwgin/utils/dingding"
	"jwgin/utils/snowflake"
	"strconv"
)

type exchange struct {
}

func (l *exchange) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	//资源列表
	Router.GET("exchange", l.get) //兑换历史
	Router.PUT("exchange", l.put) //兑换
	return Router
}

func (exchange) get(c *gin.Context) {
	uid, b2ol := c.Get("UserID")
	if !b2ol {
		RespErr(c, errors.New("请重新登录"))
		return
	}
	count, size, offset := pages(c)
	ret := []map[string]interface{}{}
	db := service.G.Model(&mysql.Exchange{}).Select("`eid`,`mobile`,`type`,exchange.addtime,exchange.uptime,`name`,`quota`")

	//订单id
	if id := c.Query("eid"); id != "" {
		db = db.Where("eid = ?", id)
	}

	//类型
	if ty := c.Query("type"); ty != "" {
		db = db.Where("exchange.type = ?", ty)
	}

	//时间
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" `addtime` > ? AND `addtime` < ? ", startTime, endTime)
	}

	err := db.Where("uid = ? ", uid).Joins("JOIN `gift` ON gift.id = exchange.gid").Count(&count).Offset(offset).Limit(size).Order("exchange.addtime DESC").Scan(&ret).Error
	if err != nil {
		RespErr(c, errors.New("fail"))
		return
	}
	RespList(c, count, ret)
}

func (exchange) put(c *gin.Context) {
	uid, b2ol := c.Get("UserID")
	if !b2ol {
		RespErr(c, errors.New("请重新登录"))
		return
	}

	q := &mysql.Exchange{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}
	if q.Gid == 0 || q.Mobile == "" {
		RespErr(c, errors.New("参数错误"))
		return
	}

	//1 先看积分够不够
	//1.1 查需要多少积分
	g := &mysql.Gift{}
	err := service.G.Model(mysql.Gift{}).Where("id = ? ", q.Gid).First(g).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	if g.Id == 0 || g.Statu != 1 {
		RespErr(c, errors.New("没有该产品或产品未上线"))
		return
	}
	if g.Num < 1 {
		RespErr(c, errors.New("该产品 被兑换完了 !!!"))
		return
	}
	//1.2 看看有多少积分
	u := &mysql.User{}
	err = service.G.Model(mysql.User{}).Where("id = ? ", uid).First(u).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	if u.Id == 0 {
		RespErr(c, errors.New("非法操作"))
		return
	}
	if u.Bean < g.Quota {
		RespErr(c, errors.New("积分不够兑换,请继续努力"))
		return
	}

	oid := snowflake.GetStringID()
	tx := service.G.Begin()
	//减用户积分
	bef := u.Bean - g.Quota
	err = tx.Table("user").Where("id = ? ", uid).Update("bean", bef).Error
	if err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}

	//减库存
	err = tx.Table("gift").Where("id = ? ", g.Id).UpdateColumn("num", gorm.Expr("num - 1")).Error
	if err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}

	Uid, err := strconv.Atoi(fmt.Sprintf("%v", uid))
	if err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	//2 积分消费记录
	i := &mysql.RecordBean{
		Uid:       Uid,
		BeforBean: u.Bean,
		Bean:      g.Quota,
		AfterBean: bef,
		Type:      2,
		Info:      "消费",
		Orderid:   oid,
	}
	err = tx.Create(i).Error
	if err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}

	//3 兑换记录
	q.Eid = oid
	q.Uid = Uid
	q.Type = 1

	err = tx.Create(q).Error
	if err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	tx.Commit()
	RespSucc(c, nil)
}
